document.addEventListener('DOMContentLoaded', function() {
    const startDateInput = document.getElementById('startDate');
    const endDateInput = document.getElementById('endDate');
    const exportBtn = document.getElementById('exportBtn');
    const statusDiv = document.getElementById('status');
    const formatSelect = document.getElementById('formatSelect');

    // 设置默认日期范围（最近 7 天）
    const today = new Date();
    const sevenDaysAgo = new Date(today);
    sevenDaysAgo.setDate(today.getDate() - 7);

    startDateInput.value = sevenDaysAgo.toISOString().split('T')[0];
    endDateInput.value = today.toISOString().split('T')[0];

    // 准备数据
    function prepareData(historyItems) {
        return historyItems.map(item => ({
            title: item.title || '无标题',
            url: item.url,
            lastVisitTime: new Date(item.lastVisitTime).toLocaleString(),
            visitCount: item.visitCount || 0
        }));
    }

    // 生成 CSV 内容
    function generateCSV(data) {
        const headers = ['标题', 'URL', '访问时间', '访问次数'];
        const rows = data.map(item => [
            item.title,
            item.url,
            item.lastVisitTime,
            item.visitCount
        ]);

        return [
            headers.join(','),
            ...rows.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
        ].join('\n');
    }

    // 生成 Excel 内容 (XLSX)
    async function generateExcel(data) {
        const ws = XLSX.utils.json_to_sheet(data);
        const wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, "历史记录");
        return XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    }

    // 生成 JSON 内容
    function generateJSON(data) {
        return JSON.stringify(data, null, 2);
    }

    exportBtn.addEventListener('click', async function() {
        const startDate = new Date(startDateInput.value);
        const endDate = new Date(endDateInput.value);
        endDate.setHours(23, 59, 59, 999);

        if (startDate > endDate) {
            statusDiv.textContent = '错误：开始日期不能晚于结束日期';
            return;
        }

        statusDiv.textContent = '正在获取历史记录...';
        exportBtn.disabled = true;

        try {
            const historyItems = await chrome.history.search({
                text: '',
                startTime: startDate.getTime(),
                endTime: endDate.getTime(),
                maxResults: 10000
            });

            if (historyItems.length === 0) {
                statusDiv.textContent = '所选时间范围内没有历史记录';
                exportBtn.disabled = false;
                return;
            }

            const data = prepareData(historyItems);
            const format = formatSelect.value;
            let content, mimeType, fileExtension;

            switch (format) {
                case 'csv':
                    content = generateCSV(data);
                    mimeType = 'text/csv;charset=utf-8';
                    fileExtension = 'csv';
                    break;
                case 'excel':
                    content = await generateExcel(data);
                    mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    fileExtension = 'xlsx';
                    break;
                case 'json':
                    content = generateJSON(data);
                    mimeType = 'application/json';
                    fileExtension = 'json';
                    break;
            }

            // 创建 Blob 对象
            const blob = new Blob([content], { type: mimeType });

            // 生成文件名
            const fileName = `browser_history_${startDateInput.value}_to_${endDateInput.value}.${fileExtension}`;

            // 下载文件
            const url = URL.createObjectURL(blob);
            await chrome.downloads.download({
                url: url,
                filename: fileName,
                saveAs: true
            });

            statusDiv.textContent = '导出成功！';
        } catch (error) {
            statusDiv.textContent = '导出失败：' + error.message;
        } finally {
            exportBtn.disabled = false;
        }
    });
});